// src/layouts/CustomLayout.tsx
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Layout, Menu, Tabs, Dropdown, Avatar, Space, Badge, Drawer, Button, message, Modal, ConfigProvider, ColorPicker  } from 'antd';
import { Link, useLocation, useNavigate, Outlet ,useModel} from 'umi';
import { normalizePath } from '@/utils/path';
import { useIntl } from '@umijs/max';
import useThemeModel from '@/utils/themeModel';
import { clearSessionToken } from '@/access';
import screenfull from 'screenfull';
import { 
  UserOutlined, 
  SettingOutlined, 
  LogoutOutlined, 
  ProfileOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined,
  BellOutlined,
  ScheduleOutlined,
  LeftOutlined,
  RightOutlined,
  SkinOutlined
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import styles from './CustomLayout.less';
import staticRoutes from '../../config/routes';
import { useOpenTab } from '@/hooks/useOpenTab';
import { initButtonActions } from '@/utils/buttonActions';
import { deepEqual, setActiveTabKey, persistTabState, removeTabState, getTabState } from '@/utils/tabPersistence';


const { Header, Content } = Layout;
const { TabPane } = Tabs;

interface MenuItem {
  menuId: number;
  name: string;
  permission: string;
  parentId: number;
  icon: string | null;
  path: string | null;
  sort: number | null;
  type: string;
  keepAlive: string;
  createTime: string | null;
  updateTime: string | null;
  delFlag: string;
  parentName: string | null;
  children?: MenuItem[];
}

interface TabPaneItem {
  key: string;
  label: string;
  path: string;
  closable: boolean;
  state?: Record<string, any>;
}

// 扩展路由类型定义
interface StaticRoute {
  path: string;
  name?: string;
  component: string;
  isTabPage?: boolean; // 标记是否为特殊选项卡页面
  routes?: StaticRoute[];
  [key: string]: any;
}

const CustomLayout: React.FC = () => {
  const intl = useIntl();
  const { initialState, setInitialState } = useModel('@@initialState');
  const { menuItems = [], currentUser ,systemConfig,avatarUrl,logoUrl} = initialState || {};
  const [themeModalVisible, setThemeModalVisible] = useState(false);
  const [themeColor, setThemeColor] = useState<string>('#0089DC');
  const [tempColor, setTempColor] = useState<string>(themeColor);
  const [activeKey, setActiveKey] = useState<string>('home');
  const [tabPanes, setTabPanes] = useState<TabPaneItem[]>([
    { key: 'home', label: intl.formatMessage({
        id: 'pages.main.menu.home',
        defaultMessage: '首页',
  }), path: "/page/main", closable: false }
  ]);
  const isUserClosingRef = useRef(false);
  const [messageVisible, setMessageVisible] = useState(false);
  const [messageCount, setMessageCount] = useState(5);
  const [scrollLeft, setScrollLeft] = useState(0);
  const [maxScrollLeft, setMaxScrollLeft] = useState(0);
  const [fullscreen, setFullscreen] = useState(false);
  const menuContainerRef = useRef<HTMLDivElement>(null);
  const location = useLocation();
  const navigate = useNavigate();
  const openTab = useOpenTab();

  // 预定义主题配置
  const themeConfigs = [
    { 
      name: '蓝色', 
      value: '#3c8dbc',
      headerBg: '#3c8dbc',
      primary: '#3c8dbc'
    },
    { 
      name: '绿色', 
      value: '#00a65a',
      headerBg: '#00a65a',
      primary: '#00a65a'
    },
    { 
      name: '紫色', 
      value: '#605ca8',
      headerBg: '#605ca8',
      primary: '#605ca8'
    },
    { 
      name: '红色', 
      value: '#d73925',
      headerBg: '#d73925',
      primary: '#d73925'
    },
    { 
      name: '橙色', 
      value: 'rgb(255, 160, 77)',
      headerBg: 'linear-gradient(90deg, rgb(255, 160, 77) 0%, rgb(255, 119, 0) 100%)',
      primary: '#FFA04D'
    },
    { 
      name: '科技蓝', 
      value: 'rgb(0, 137, 220)',
      headerBg: 'linear-gradient(90deg, rgb(0, 137, 220) 0%, rgb(1, 88, 186) 100%)',
      primary: '#0089DC'
    }
  ];

  // 更新主题颜色
  const updateTheme = (color: string) => {
    setThemeColor(color);
    // 将主题存储到 localStorage
    localStorage.setItem('themeColor', color);
  };


  useEffect(() => {
    initButtonActions(openTab);
  }, [openTab]);

 

  // 初始化主题
  useEffect(() => {
    const savedTheme = localStorage.getItem('themeColor');
    if (savedTheme) {
      setThemeColor(savedTheme);
    }
  
   // 恢复选项卡状态
   const savedTabs = sessionStorage.getItem('tabPanes');
   const savedActiveKey = sessionStorage.getItem('activeTabKey');
   
   if (savedTabs) {
     try {
       const parsedTabs = JSON.parse(savedTabs);
       setTabPanes(parsedTabs);
       
       // 恢复活动选项卡状态
       if (savedActiveKey) {
         const savedState = getTabState(savedActiveKey);
         const tab = parsedTabs.find((t: any) => t.key === savedActiveKey);
         
         // 关键修复：确保路径匹配时才恢复状态
         if (tab && tab.path === location.pathname) {
           setActiveKey(savedActiveKey);
           
           // 如果状态不匹配，恢复保存的状态
           if (savedState && !deepEqual(location.state, savedState)) {
             navigate(tab.path, {
               state: savedState,
               replace: true
             });
           }
         }
       }
     } catch (error) {
       console.error('恢复选项卡状态失败:', error);
     }
   }
  }, []);

 // 保存选项卡状态
 useEffect(() => {
    sessionStorage.setItem('tabPanes', JSON.stringify(tabPanes));
  }, [tabPanes]);

  useEffect(() => {
    if (activeKey) {
      sessionStorage.setItem('activeTabKey', activeKey);
      setActiveTabKey(activeKey);
    }
  }, [activeKey]);

  const openGlobalTab = useCallback((key: string, label: string, path: string, state?: any) => {
    // 检查是否已存在相同路径和状态的选项卡
    const existingTab = tabPanes.find(tab => 
      tab.path === path && 
      deepEqual(tab.state, state)
    );
    
    if (existingTab) {
      // 存在相同状态，激活现有选项卡
      setActiveKey(existingTab.key);
      navigate(path, { state, replace: true });
      return;
    }
    
    // 创建新选项卡
    setTabPanes(prev => [...prev, {
      key,
      label,
      path,
      closable: true,
      state
    }]);
    console.log("openGlobalTab------",key)
    setActiveKey(key);
    navigate(path, { state });
    persistTabState(key, state);
  }, [tabPanes, navigate]);


  const getHeaderBg = () => {
    const theme = themeConfigs.find(t => t.value === themeColor);
    return theme ? theme.headerBg : '#3c8dbc';
  };

  // 获取当前主题的主色
  const getPrimaryColor = () => {
    const theme = themeConfigs.find(t => t.value === themeColor);
    return theme ? theme.primary : '#3c8dbc';
  };

  // 监听全屏状态变化
  useEffect(() => {
    if (screenfull.isEnabled) {
      const handleChange = () => {
        setFullscreen(screenfull.isFullscreen);
      };
      
      screenfull.on('change', handleChange);
      
      return () => {
        screenfull.off('change', handleChange);
      };
    }
  }, []);

  // 切换全屏
  const toggleFullscreen = () => {
    if (screenfull.isEnabled) {
      screenfull.toggle();
    } else {
      message.warning('您的浏览器不支持全屏功能');
    }
  };

  // 用户下拉菜单
  const userMenuItems: MenuProps['items'] = [
    {
      key: 'fullscreen',
      label: fullscreen ? intl.formatMessage({ id: 'pages.main.userMenu.fullscreen.show', defaultMessage: '全屏展示'}) : intl.formatMessage({ id: 'pages.main.userMenu.fullscreen.exit', defaultMessage: '全屏展示'}),
      icon: fullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />,
      onClick: toggleFullscreen
    },
    {
      key: 'profile',
      label: intl.formatMessage({ id: 'pages.main.userMenu.profile', defaultMessage: '个人资料'}),
      icon: <ProfileOutlined />,
      onClick: () => handleOpenPage('account', intl.formatMessage({ id: 'pages.main.userMenu.profile', defaultMessage: '个人资料'}), '/account/center')
    },
    {
      key: 'password',
      label: intl.formatMessage({ id: 'pages.main.userMenu.password', defaultMessage: '修改密码'}),
      icon: <SettingOutlined />
    },
    {
      key: 'security',
      label: intl.formatMessage({ id: 'pages.main.userMenu.security', defaultMessage: '修改密保'}),
      icon: <SettingOutlined />
    },
    {
        key: 'switchSkin',
        label: intl.formatMessage({ id: 'pages.main.userMenu.switchSkin', defaultMessage: '切换主题'}),
        icon: <SkinOutlined />,
        onClick: () => {
            setTempColor(themeColor);
            setThemeModalVisible(true);
        }
    },
    { type: 'divider' },
    {
      key: 'logout',
      label: intl.formatMessage({ id: 'pages.main.userMenu.logout', defaultMessage: '退出登录'}),
      icon: <LogoutOutlined />,
      onClick: () => {
        clearSessionToken();
        // 2. 跳转登录页
        navigate('/login', { replace: true });
        // 3. 强制刷新页面清除状态
        window.location.reload();
        // message.success('已退出登录');
      }
    }
  ];
  
  // 路由匹配函数
  const matchRoute = (path: string, menuPath: string | null): boolean => {
    if (!menuPath) return false;
    // 支持带参数的路由匹配
    const baseMenuPath = menuPath.split(':')[0].replace(/\/$/, '');
    return path === menuPath || path.startsWith(`${baseMenuPath}/`);
  };

  // 查找菜单项
  const findMenuByPath = useCallback((menus: MenuItem[], path: string): MenuItem | null => {
    for (const menu of menus) {
      if (menu.path && matchRoute(path, menu.path)) {
        return menu;
      }
      if (menu.children) {
        const found = findMenuByPath(menu.children, path);
        if (found) return found;
      }
    }
    return null;
  }, []);

  // 查找菜单项
  const findMenuById = (menus: MenuItem[], menuId: number): MenuItem | null => {
    for (const menu of menus) {
      if (menu.menuId === menuId) return menu;
      if (menu.children) {
        const found = findMenuById(menu.children, menuId);
        if (found) return found;
      }
    }
    return null;
  };

  // 打开页面
  const handleOpenPage = (key: string, label: string, path: string, state?: any) => {
    setTabPanes(prev => {
      const exists = prev.some(tab => tab.key === key);
      return exists ? prev : [...prev, { key, label, path, closable: true }];
    });
    console.log("handleOpenPage---",key)
    setActiveKey(key);
    navigate(path, { state });
  };

  // 菜单点击处理
  const handleMenuClick = useCallback((menu: MenuItem) => {
    if (!menu.path) return;

    const tabKey = menu.menuId.toString();
    const normalizedPath = normalizePath(menu.path); // 处理路径格式
    setTabPanes(prev => {
      const exists = prev.some(tab => tab.key === tabKey);
      return exists ? prev : [...prev, {
        key: tabKey,
        label: menu.name,
        path: normalizedPath,
        closable: true
      }];
    });
    console.log("handleMenuClick---",tabKey)
    setActiveKey(tabKey);
    navigate(normalizedPath);
  }, [navigate]);

  // 在静态路由中查找匹配的路由
  const findRouteInStatic = useCallback((path: string): StaticRoute | null => {
    // 支持更灵活的参数化路径匹配
    const findRecursive = (routes: StaticRoute[]): StaticRoute | null => {
      for (const route of routes) {
        // 处理动态参数路径（如 /detail/:id）
        if (route.path?.includes(':')) {
          const pattern = new RegExp(
            `^${route.path.replace(/:[^/]+/g, '([^/]+)')}$`
          );
          
          if (pattern.test(path)) {
            return route;
          }
        }
        // 精确匹配
        else if (route.path === path) {
          return route;
        }
        
        // 子路由递归
        if (route.routes) {
          const found = findRecursive(route.routes);
          if (found) return found;
        }
      }
      return null;
    };
    
    return findRecursive(staticRoutes);
  }, []);

  useEffect(() => {
    // 1. 处理特殊场景（如关闭所有选项卡）
    if (location.pathname === '/dashboard') {
      setTabPanes(prev => prev.filter(tab => tab.key !== activeKey));
      setActiveKey('home');
      return;
    }
    
    // 2. 跳过不需要处理的路径
    if (location.pathname === '/' || isUserClosingRef.current) {
      return;
    }
    
    const tabKey = location.state?._tabKey;
    const tabTitle = location.state?._tabTitle;
    
    if (tabKey && tabTitle) {
      setTabPanes(prev => {
        const exists = prev.some(tab => tab.key === tabKey);
        return exists ? prev : [...prev, {
          key: tabKey,
          label: tabTitle,
          path: location.pathname,
          closable: true,
          state: location.state
        }];
      });
      console.log("处理通过 openTab 打开的新选项卡",tabKey)
      setActiveKey(tabKey);
      persistTabState(tabKey, location.state);
      return;
    }

    const matchedMenu = findMenuByPath(menuItems, location.pathname);
    if (matchedMenu) {
      const tabKey = matchedMenu.menuId.toString();
      
      setTabPanes(prev => {
        const exists = prev.some(tab => tab.key === tabKey);
        return exists ? prev : [...prev, {
          key: tabKey,
          label: matchedMenu.name,
          path: matchedMenu.path || '',
          closable: true,
          state: undefined
        }];
      });
      
      setActiveKey(tabKey);
      return;
    }
    
  }, [location.pathname, location.state])

  // 渲染菜单项
  const renderMenuItems = useCallback((menus: MenuItem[]): MenuProps['items'] => {
    return menus.map(menu => {
      const hasChildren = menu.children && menu.children.length > 0;
      
      return {
        key: menu.menuId.toString(),
        label: hasChildren ? menu.name : (
          <span onClick={() => handleMenuClick(menu)}>
            {menu.name}
          </span>
        ),
        icon: menu.icon && <span className={`iconfont ${menu.icon}`} />,
        children: hasChildren ? renderMenuItems(menu.children!) : undefined,
        onClick: !hasChildren ? () => handleMenuClick(menu) : undefined
      };
    });
  }, [handleMenuClick]);
  
  // 计算菜单滚动
  useEffect(() => {
    if (menuContainerRef.current) {
      const container = menuContainerRef.current;
      const updateMaxScroll = () => {
        setMaxScrollLeft(container.scrollWidth - container.clientWidth);
      };
      
      updateMaxScroll();
      window.addEventListener('resize', updateMaxScroll);
      return () => window.removeEventListener('resize', updateMaxScroll);
    }
  }, [menuItems]);

  // 处理选项卡更改
  const handleTabChange = useCallback((key: string) => {
    const targetTab = tabPanes.find(tab => tab.key === key);
    if (targetTab) {
      // 关键修改：导航时携带存储的状态
      navigate(targetTab.path, {
        state: targetTab.state || {}, // 传递保存的状态
        replace: true // 避免创建新历史记录
      });
      console.log("handleTabChange---",key)
      setActiveKey(key);
    }
  }, [tabPanes, navigate]);

  // 删除选项卡
  const removeTab = useCallback((targetKey: string) => {
    try {
        if (targetKey === 'home') return;
        isUserClosingRef.current = true;
        setTabPanes(prevPanes => {
            try {
                const newTabs = prevPanes.filter(tab => tab.key !== targetKey);
                if (newTabs.length === 0) {
                    throw new Error(intl.formatMessage({ id: 'pages.main.tab.closeAllHint', defaultMessage: '不能关闭所有标签页'}));
                }
                return newTabs;
            } catch (error) {
                console.error('更新标签页失败:', error);
                return prevPanes;
            }
        });
        removeTabState(targetKey);
        // 导航到上一个标签或首页
        const remainingTabs = tabPanes.filter(tab => tab.key !== targetKey);
        const lastTab = remainingTabs[remainingTabs.length - 1];
        const newPath = lastTab?.path || '/page/main';
        // 使用 setTimeout 确保状态更新后再导航
        setTimeout(() => {
        navigate(newPath);
        isUserClosingRef.current = false; // 重置标记
        }, 0); 
        console.log("removeTab---",lastTab?.key)
        setActiveKey(lastTab?.key || 'home');
    } catch (error) {
        console.error('关闭标签页失败:', error);
        message.error(intl.formatMessage({ id: 'pages.main.tab.closeError', defaultMessage: '关闭标签页时出错'}));
  }
  }, [tabPanes, navigate]);

  useEffect(() => {
    // 全局打开选项卡事件
    const handleOpenGlobalTab = (e: CustomEvent) => {
      const { key, label, path, state } = e.detail;
      openGlobalTab(key, label, path, state);
    };
    
    // 全局关闭选项卡事件
    const handleCloseCurrentTab = (e: CustomEvent) => {
      const { navigateTo } = e.detail;
      removeTab(activeKey);
      if (navigateTo) {
        setTimeout(() => navigate(navigateTo), 100);
      }
    };
    
    window.addEventListener('open-global-tab', handleOpenGlobalTab as EventListener);
    window.addEventListener('close-current-tab', handleCloseCurrentTab as EventListener);
    
    return () => {
      window.removeEventListener('open-global-tab', handleOpenGlobalTab as EventListener);
      window.removeEventListener('close-current-tab', handleCloseCurrentTab as EventListener);
    };
  }, [openGlobalTab, activeKey, removeTab, navigate]);

  // 初始化全局方法
  useEffect(() => {
    // 挂载全局打开选项卡方法
    window.openGlobalTab = openGlobalTab;
    
    // 挂载全局关闭当前选项卡方法
    window.closeCurrentTab = (navigateTo?: string) => {
      removeTab(activeKey);
      if (navigateTo) {
        setTimeout(() => navigate(navigateTo), 100);
      }
    };
    
    // 挂载全局关闭指定路径选项卡方法
    window.closeTabByPath = (path: string) => {
      const tabToClose = tabPanes.find(tab => tab.path === path && tab.key !== 'home');
      if (tabToClose) {
        removeTab(tabToClose.key);
      }
    };
    
    return () => {
      delete window.openGlobalTab;
      delete window.closeCurrentTab;
      delete window.closeTabByPath;
    };
  }, [openGlobalTab, activeKey, tabPanes, removeTab, navigate]);

  const scrollMenu = useCallback((direction: 'left' | 'right') => {
    if (menuContainerRef.current) {
      const container = menuContainerRef.current;
      const scrollAmount = container.clientWidth * 0.7;
      const currentScroll = container.scrollLeft;
      const containerWidth = container.clientWidth;
      const contentWidth = container.scrollWidth;
      
      let newScrollLeft;
      
      if (direction === 'left') {
        newScrollLeft = Math.max(0, currentScroll - scrollAmount);
      } else {
        // 计算确保最后一个菜单项完全可见
        const maxScroll = contentWidth - containerWidth;
        newScrollLeft = Math.min(
          maxScroll + 30, // 额外滚动距离
          currentScroll + scrollAmount
        );
        
        // 如果已经接近最右，直接滚动到最右
        if (currentScroll >= maxScroll - 50) {
          newScrollLeft = maxScroll + 30;
        }
      }
      
      container.scrollTo({ left: newScrollLeft, behavior: 'smooth' });
      setScrollLeft(newScrollLeft);
    }
  }, [maxScrollLeft]);


  // 右键菜单点击事件
  const renderTabContextMenu = useCallback((key: string) => {
    const currentTab = tabPanes.find(tab => tab.key === activeKey);
    return {
      items: [
        { 
          key: 'close', 
          label: intl.formatMessage({ id: 'pages.main.tab.close', defaultMessage: '关闭当前'}), 
          disabled: key === 'home',
          onClick: () => removeTab(key)
        },
        { 
          key: 'closeOthers', 
          label: intl.formatMessage({ id: 'pages.main.tab.closeOthers', defaultMessage: '关闭其他'}),
          onClick: () => {
              const homeTab = tabPanes.find(tab => tab.key === 'home');
              const currentTab = tabPanes.find(tab => tab.key === key);
              const newTabs = [];
              if (homeTab) newTabs.push(homeTab);
              if (currentTab && currentTab.key !== 'home') newTabs.push(currentTab);
              
              setTabPanes(newTabs);
              setActiveKey(key);
          }
        },
        { 
          key: 'closeAll', 
          label: intl.formatMessage({ id: 'pages.main.tab.closeAll', defaultMessage: '关闭所有'}),
          onClick: () => {
            const homeTab = tabPanes.find(tab => tab.key === 'home');
            setTabPanes(homeTab ? [homeTab] : []);
            if (key !== 'home') {
              setActiveKey('home');
              navigate('/page/main');
            }
          }
        }
      ]
    };
  }, [tabPanes, removeTab, navigate]);

  // 任务管理
  const handleTaskClick = useCallback(() => {
    const taskKey = 'task-management';
    if (!tabPanes.some(pane => pane.key === taskKey)) {
      setTabPanes([...tabPanes, {
        key: taskKey,
        label: intl.formatMessage({ id: 'pages.main.menu.taskManagement', defaultMessage: '任务管理'}),
        path: "",
        closable: true
      }]);
    }
    setActiveKey(taskKey);
  }, [tabPanes]);

  // 消息管理
  const handleMessageClick = useCallback(() => {
    setMessageVisible(true);
    setMessageCount(0);
  }, []);

  const handleBeianClick = (): void => {
    Modal.confirm({
      title: '系统提示',
      content: '是否跳转工信部网站',
      onOk: () => {
        window.open('https://beian.miit.gov.cn/#/Integrated/index');
      },
    });
  };

  return (
    <ConfigProvider theme={{ token:  { colorPrimary: getPrimaryColor() }}}>
    <Layout className={styles.layout}>
      <Header 
        className={styles.header}
        style={{ 
            background: getHeaderBg(),
            transition: 'background 0.3s ease'
        }}>
        <div className={styles.headerLeft}>
          <div className={styles.logoContainer}>
            <img src={logoUrl} alt="logo" className={styles.logoImg} />
          </div>
          <div className={styles.systemTitle}>{systemConfig.systemName}</div>
        </div>
        
        <div className={styles.headerRight}>
          <div className={styles.navContainer}>
            {scrollLeft > 0 && (
              <Button 
                className={styles.scrollButton} 
                icon={<LeftOutlined />}
                onClick={() => scrollMenu('left')}
              />
            )}
            
            <div className={styles.menuWrapper} ref={menuContainerRef}>
              <Menu
                theme="light"
                mode="horizontal"
                items={renderMenuItems(menuItems)}
                selectedKeys={[activeKey === 'home' ? '' : activeKey]}
                className={styles.navMenu}
                onClick={({key}) => {
                    const menuId = parseInt(key);
                    const menu = findMenuById(menuItems, parseInt(key));
                    if (menu?.path) {
                        const tabKey = key;
                        setTabPanes(prev => {
                          const exists = prev.some(tab => tab.key === tabKey);
                          return exists ? prev : [...prev, {
                            key: tabKey,
                            label: menu.name,
                            path: menu.path,
                            closable: true
                          }];
                        });
                        
                        setActiveKey(tabKey);
                        navigate(menu.path);
                      }
                  }}
              />
            </div>
            
            {scrollLeft < maxScrollLeft && (
              <Button 
                className={styles.scrollButton} 
                icon={<RightOutlined />}
                onClick={() => scrollMenu('right')}
              />
            )}
            
            <div className={styles.iconArea}>
              <ScheduleOutlined 
                className={styles.icon} 
                onClick={handleTaskClick}
              />
              <Badge count={messageCount} size="small" className={styles.badge}>
                <BellOutlined 
                  className={styles.icon} 
                  onClick={handleMessageClick}
                />
              </Badge>
            </div>
            
            <Dropdown 
              menu={{ items: userMenuItems }} 
              placement="bottomRight"
              overlayClassName={styles.userDropdown}
            >
              <Space className={styles.userInfo}>
                <Avatar 
                  size="default" 
                  src={avatarUrl} 
                  icon={<UserOutlined />}
                />
                <span className={styles.userName}>{currentUser.username}</span>
              </Space>
            </Dropdown>
          </div>
          
          <div className={styles.tabsContainer}>
          <Tabs
            type="editable-card"
            activeKey={activeKey}
            onChange={handleTabChange}
            onEdit={removeTab}
            hideAdd
            className={styles.tabs}
            items={tabPanes.map(pane => ({
                key: pane.key,
                label: (
                    <Dropdown 
                      menu={renderTabContextMenu(pane.key)}
                      trigger={['contextMenu']}
                      overlayClassName={styles.tabDropdown}
                      overlayStyle={{ zIndex: 1050 }}
                      destroyOnClose
                    >
                      <div style={{
                        padding: '8px 16px',
                        margin: '-8px -16px',
                        height: '100%',
                        display: 'inline-flex',
                        alignItems: 'center'
                      }}>
                        {pane.label}
                        {pane.closable && (
                          <span 
                            className="ant-tabs-tab-remove"
                            onClick={(e) => {
                              e.stopPropagation();
                              removeTab(pane.key);
                            }}
                          />
                        )}
                      </div>
                    </Dropdown>
                ),
                closable: pane.closable
            }))}
            />
          </div>
        </div>
      </Header>
      
      <Drawer
        title={intl.formatMessage({ id: 'pages.main.modal.message.title', defaultMessage: '消息通知'})}
        placement="right"
        width={350}
        open={messageVisible}
        onClose={() => setMessageVisible(false)}
        maskClosable={true}
      >
        <div className={styles.messageContent}>
        </div>
      </Drawer>
      {/* 主题切换弹窗 */}
      <Modal
        title={intl.formatMessage({ id: 'pages.main.modal.theme.title', defaultMessage: '选择主题颜色'})}
        open={themeModalVisible}
        onOk={() => {
          updateTheme(tempColor);
          setThemeModalVisible(false);
        }}
        onCancel={() => setThemeModalVisible(false)}
        okText={intl.formatMessage({ id: 'pages.main.theme.button.ok', defaultMessage: '应用'})}
        cancelText={intl.formatMessage({ id: 'pages.main.theme.button.cancal', defaultMessage: '取消'})}
        className={styles.themeModal}
      >
        <div className={styles.themeColors}>
          {themeConfigs.map((theme) => (
            <div 
              key={theme.value}
              className={styles.colorBlock}
              style={{ background: theme.headerBg }}
              onClick={() => setTempColor(theme.value)}
            >
              <div className={`${styles.colorCheck} ${tempColor === theme.value ? styles.active : ''}`}>
                {tempColor === theme.value && <span className={styles.checkIcon}>✓</span>}
              </div>
              <span className={styles.colorName}>{theme.name}</span>
            </div>
          ))}
        </div>
      </Modal>

      <Content className={styles.content}>
        <div className={styles.contentContainer}>
          <Outlet />
        </div>
      </Content>
      <div className={styles.footer}>
            <div className={styles.copyright}>
            Copyright &copy; 2023 银雁 | <a onClick={handleBeianClick}>粤ICP备18013953号</a>
            </div>
      </div>
    </Layout>
    </ConfigProvider>
  );
};

export default CustomLayout;